package com.ztf0337.mycurriculumdesign.adapter;

import android.annotation.SuppressLint;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.ztf0337.mycurriculumdesign.R;
import com.ztf0337.mycurriculumdesign.Utils.CompareClassUtil;
import com.ztf0337.mycurriculumdesign.Utils.TransitionUtils;
import com.ztf0337.mycurriculumdesign.entity.Order;
import com.ztf0337.mycurriculumdesign.entity.ParkingSpace;

import java.util.ArrayList;
import java.util.List;

public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {
    private List<Order> orderList;
    private OrderAdapter.OnItemClickListener listener;  // 监听器引用
    private List<Order> selectOrders = new ArrayList<>();
    public OrderAdapter(List<Order> orderList) {
        this.orderList = orderList;
    }

    // 定义点击事件接口
    public interface OnItemClickListener {
        void onItemClick(Order order);
    }

    // 提供设置监听器的方法
    public void setOnItemClickListener(OrderAdapter.OnItemClickListener listener) {
        this.listener = listener;
    }

    private boolean isSelectionMode = false;

    // 提供外部调用的方法
    @SuppressLint("NotifyDataSetChanged")
    public void setSelectionMode(boolean selectionMode) {
        isSelectionMode = selectionMode;
        notifyDataSetChanged(); // 通知刷新所有 item
    }


    @NonNull
    @Override
    public OrderAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_order, parent, false);
        return new OrderAdapter.ViewHolder(view);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onBindViewHolder(@NonNull OrderAdapter.ViewHolder holder, int position) {
        Order order = orderList.get(position);
        holder.tvOrderNumber.setText("订单号："+order.getOrderNumber());
        holder.tvOrderInfo.setText("停车位："
                + order.getParkingSpaceNumber());
        holder.tvOrderTimeStatus.setText("时间："+order.getStartTime()
                + "   状态："
                + (order.getTransactionStatus() ? "已结束" : "进行中"));
        // 给每个item绑定点击事件，调用回调接口
        holder.checkBox.setVisibility((isSelectionMode && order.getTransactionStatus()) ? View.VISIBLE : View.GONE);
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(order);
            }
        });
        // 先解绑避免复用时错乱
        holder.checkBox.setOnCheckedChangeListener(null);
        // 这里设置勾选状态，判断选中列表中是否包含当前order的id
        holder.checkBox.setChecked(selectOrders.contains(order));
        holder.checkBox.setOnClickListener(v -> {
            if (holder.checkBox.isChecked()) {
                if (!selectOrders.contains(order)) {
                    selectOrders.add(order);
                }
            } else {
                selectOrders.remove(order);
            }
        });
    }

    @Override
    public int getItemCount() {
        return orderList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvOrderNumber, tvOrderInfo,tvOrderTimeStatus;
        CheckBox checkBox;

        public ViewHolder(View view) {
            super(view);
            tvOrderNumber = view.findViewById(R.id.tvOrderNumber);
            tvOrderInfo = view.findViewById(R.id.tvOrderInfo);
            tvOrderTimeStatus = view.findViewById(R.id.tvOrderTimeStatus);
            checkBox = view.findViewById(R.id.cbSelect);
        }
    }

    // 更新整个数据集
    @SuppressLint("NotifyDataSetChanged")
    public void updateData(List<Order> newData) {
        this.orderList = newData;
        notifyDataSetChanged();  // 简单刷新全部（低效）
    }

    // 只新增一项
    public void addItem(Order newItem) {
        orderList.add(newItem);
        notifyItemInserted(orderList.size() - 1);
    }

    // 修改一项
    public void updateItem(Order newItem) {
        orderList.set(CompareClassUtil.compareOrder(orderList,newItem), newItem);
        notifyItemChanged(CompareClassUtil.compareOrder(orderList,newItem));
    }

    // 删除一项
    public void removeItem(Order newItem) {
        int index = CompareClassUtil.compareOrder(orderList, newItem);
        if (index != -1) {
            orderList.remove(index);
            notifyItemRemoved(index);
        }
    }

    public List<Order> getSelectOrdersAndClear() {
        List<Order> selected = new ArrayList<>(selectOrders); // 先复制一份当前选中ID
        selectOrders.clear();  // 清空原列表
        return selected;        // 返回复制的列表
    }

    public void clearSelect() {
        selectOrders.clear();  // 清空原列表
    }
}
